package com.common.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.entity.A_adminer;
import com.common.utils.StringUtils;
import com.lyk.service.A_adminerService;
import com.lyk.service.impl.A_adminerServiceImpl;

public class LoginServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {
		
		//得到用户的浏览器信息
		String Agent = request.getHeader("User-Agent");
		StringTokenizer st = new StringTokenizer(Agent,";");
		st.nextToken();
		String userbrowser = st.nextToken();
		//得到用户的登录IP
		String ip = request.getHeader("x-forwarded-for");
		InetAddress inet=null;
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {

              ip = request.getHeader("Proxy-Client-IP");

        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {

                   ip = request.getHeader("WL-Proxy-Client-IP");

        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {

             ip = request.getRemoteAddr();
             if(ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")){  
                 //根据网卡取本机配置的IP  
                 try {  
                     inet = InetAddress.getLocalHost();  
                 } catch (UnknownHostException e) {  
                     e.printStackTrace();  
                 }  
                 ip= inet.getHostAddress();  
             }  

        }
		//获取用户名和密码
		String loginID = request.getParameter("loginID");
		String password = request.getParameter("password");
		
		Integer admin_id = StringUtils.str2Integer(loginID, 0);
		A_adminerService adminerService = new A_adminerServiceImpl();
		A_adminer adminer = adminerService.findById(admin_id);
		if(adminer != null){
			String admin_pwd = adminer.getAdmin_pwd();
			if(password.equals(admin_pwd)){
				
					request.getSession().setAttribute("userInfo", adminer);
					request.getSession().setAttribute("browser", userbrowser);
					request.getSession().setAttribute("actip", ip);
					request.getRequestDispatcher("login_onlineServlet").forward(request, resp);
				
			}else{
				request.setAttribute("msg", "用户名或密码输入错误");
				request.getRequestDispatcher("login1.jsp").forward(request, resp);
			}
		}else{
			request.setAttribute("msg", "用户名或密码输入错误");
			request.getRequestDispatcher("login1.jsp").forward(request, resp);
		}
	}
}
